package com.shasselclub.api.v1;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSON;
import com.shasselclub.api.v1.param.AcIdParam;
import com.shasselclub.api.v1.param.ShareOpenIdParam;
import com.shasselclub.api.v1.param.SnsapiUserInfoParam;
import com.shasselclub.api.v1.param.WeiXinShareConfigParam;
import com.shasselclub.api.v1.result.WeiXinShareResult;
import com.shasselclub.api.v1.result.WeiXinShareUserResult;
import com.shasselclub.api.v1.result.WeiXinUserResult;
import com.shasselclub.api.v1.service.RedisService;
import com.shasselclub.api.v1.service.ValidParamService;
import com.shasselclub.api.weixin.WechatUtil;
import com.shasselclub.api.weixin.WxWebPageAccessToken;
import com.shasselclub.api.weixin.WxWebPageUserinfo;
import com.shasselclub.api.weixin.common.JsApiTicketUtil;
import com.shasselclub.api.weixin.common.RandomStr;
import com.shasselclub.api.weixin.common.Sha1;
import com.shasselclub.common.constant.ResultModel;
import com.shasselclub.common.constant.ResultStatus;
import com.shasselclub.common.utils.DateUtils;
import com.shasselclub.common.utils.IpUtils;
import com.shasselclub.common.utils.UrlUtils;
import com.shasselclub.common.utils.map.GetParamToMap;
import com.shasselclub.common.utils.string.StringUtil;
import com.shasselclub.project.ask.datiRecord.domain.DatiRecord;
import com.shasselclub.project.ask.datiRecord.service.IDatiRecordService;
import com.shasselclub.project.ask.problem.service.IProblemService;
import com.shasselclub.project.ask.question.domain.Question;
import com.shasselclub.project.ask.question.service.IQuestionService;
import com.shasselclub.project.ask.weixinUser.domain.WeixinUser;
import com.shasselclub.project.ask.weixinUser.service.IWeixinUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.xmlbeans.impl.jam.JamServiceParams;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Slf4j
@RestController
@RequestMapping(value = "/api/weixin", produces = "application/json;charset=UTF-8")
@Api(value = "微信接口", tags  = "微信接口",description = "2")
public class WeiXinApi {

    @Autowired
    private IQuestionService questionService;

    @Autowired
    private IWeixinUserService weixinUserService;
    @Autowired
    private RedisService redisService;
    @Autowired
    private ValidParamService validParamService;
    @Autowired
    private IDatiRecordService datiRecordService;
    /**
     * @description: 手动网页授权，获取用户的基本信息
     * @author: 郑云飞
     * @return: java.lang.String

    @ApiOperation(notes = "网页授权，获取用户的基本信息,<br>" +
            "参数code获取方式<br>" +
            "参考1：<a href='https://developers.weixin.qq.com/doc/offiaccount/OA_Web_Apps/Wechat_webpage_authorization.html'>微信官网</a>" +
            "参考2：<a href='https://blog.csdn.net/bzf0482/article/details/108527441'>获取code</a>", value = "网页授权，获取用户的基本信息",response = WeiXinUserResult.class,position =1 )
    @GetMapping("/snsapi_userinfo")
    public Object snsapi_userinfo(@Valid SnsapiUserInfoParam param, BindingResult bindingResult, HttpServletRequest request){
        WxWebPageUserinfo wxWebPageUserinfo = new WxWebPageUserinfo();
        ResultModel resultModel=new ResultModel();
        try {
            Map<String, Object> parameterMap= GetParamToMap.getParameterMap(request);
            Map<String, Object> jsonMap= GetParamToMap.getJosnParameterMap(request);
            log.info("传递过来的参数==="+ JSON.toJSONString(parameterMap)+"ip==="+ IpUtils.getIpAddr(request));
            log.info("传递过来的jsonMap参数==="+ JSON.toJSONString(jsonMap)+"ip==="+ IpUtils.getIpAddr(request));
            if (validParamService.validParam(bindingResult, resultModel)){
                return resultModel;
            }
            String code=param.getCode();
            WxWebPageAccessToken wxWebPageAccessToken = WechatUtil.getAccessTokenAndOpenid(code);
            log.info(wxWebPageAccessToken.toString());
            wxWebPageUserinfo = WechatUtil.getUserinfo(wxWebPageAccessToken.getAccess_token(), wxWebPageAccessToken.getOpenid());
            log.info("获取到的微信基本信息2", JSON.toJSONString(wxWebPageUserinfo));
            Map<String,Object> queryMap=new HashMap<>();
            queryMap.put("openId",wxWebPageUserinfo.getOpenid());
            int count=weixinUserService.count(queryMap);
            log.info("根据openId查询到的总条数：{}",count);
            WeixinUser weixinUser=new WeixinUser();
            weixinUser.setOpenId(wxWebPageUserinfo.getOpenid());
            weixinUser.setNickName(wxWebPageUserinfo.getNickname());
            weixinUser.setHeadImgUrl(wxWebPageUserinfo.getHeadimgurl());
            weixinUser.setProvince(wxWebPageUserinfo.getProvince());
            weixinUser.setCountry(wxWebPageUserinfo.getCountry());
            weixinUser.setCity(wxWebPageUserinfo.getCity());
            weixinUser.setSex(wxWebPageUserinfo.getSex()+"");
            if(count==0){
                //新增微信用户信息
                log.info("新增微信基本信息参数：{}",JSON.toJSONString(weixinUser));
                int addCount=weixinUserService.insertWeixinUser(weixinUser);
                log.info("新增微信基本信息返回结果：{}",addCount);
            }
            WeiXinUserResult weiXinUserResult = WeiXinUserResult.boToResult(wxWebPageUserinfo);
            resultModel.setCode(ResultStatus.SUCCESS.getCode());
            resultModel.setMessage(ResultStatus.SUCCESS.getMessage());
            resultModel.setData(weiXinUserResult);
        } catch (Exception e) {
            resultModel.setCode(ResultStatus.ERROR.getCode());
            resultModel.setMessage("网页授权，获取用户的基本信息出错了");
            log.error("网页授权，获取用户的基本信息出错了", e.toString());
            e.printStackTrace();

        }
        return resultModel;
    }
     */

    @ApiOperation(notes = "根据acId获取微信登录信息" , value = "根据acId获取微信登录信息",response = WeiXinShareResult.class,position =2)
    @RequestMapping(value = "/getWeiXinUserInfo",method = RequestMethod.POST)
    public Object getWeiXinUserInfo(@Valid AcIdParam param, BindingResult bindingResult, HttpServletRequest request){
        ResultModel resultModel=new ResultModel();
        try{
            Map<String, Object> parameterMap= GetParamToMap.getParameterMap(request);
            Map<String, Object> jsonMap= GetParamToMap.getJosnParameterMap(request);
            log.info("传递过来的参数==="+ JSON.toJSONString(parameterMap)+"ip==="+ IpUtils.getIpAddr(request));
            log.info("传递过来的jsonMap参数==="+ JSON.toJSONString(jsonMap)+"ip==="+ IpUtils.getIpAddr(request));
            if (validParamService.validParam(bindingResult, resultModel)){
                return resultModel;
            }
            String acId=param.getAcId();
           if(!redisService.exists(acId)) {
               resultModel.setCode(ResultStatus.ERROR.getCode());
               resultModel.setMessage("acId不正确");
               return resultModel;
           }
            WeiXinUserResult weiXinUserResult= (WeiXinUserResult) redisService.get(acId);
            resultModel.setCode(ResultStatus.SUCCESS.getCode());
            resultModel.setMessage(ResultStatus.SUCCESS.getMessage());
            resultModel.setData(weiXinUserResult);
        }catch (Exception e){
            e.printStackTrace();
            resultModel.setCode(ResultStatus.ERROR.getCode());
            resultModel.setMessage("获取微信配置信息出错");
        }
        return resultModel;
    }

    /**
     * 获取微信分享配置的请求
     * @param param 前台传过来的当前页面的请求地址
     * @return
     */
    @ApiOperation(notes = "获取微信分享配置信息-邀请好友助力时调用" , value = "获取微信分享配置信息",response = WeiXinShareResult.class,position =2)
    @RequestMapping(value = "/getWxConfig",method = RequestMethod.POST)
    public Object share(@Valid WeiXinShareConfigParam param, BindingResult bindingResult, HttpServletRequest request){
        ResultModel resultModel=new ResultModel();
        try{
            Map<String, Object> parameterMap= GetParamToMap.getParameterMap(request);
            Map<String, Object> jsonMap= GetParamToMap.getJosnParameterMap(request);
            log.info("传递过来的参数==="+ JSON.toJSONString(parameterMap)+"ip==="+ IpUtils.getIpAddr(request));
            log.info("传递过来的jsonMap参数==="+ JSON.toJSONString(jsonMap)+"ip==="+ IpUtils.getIpAddr(request));
            if (validParamService.validParam(bindingResult, resultModel)){
                return resultModel;
            }
            String domain=request.getServerName();
            String shareLink=param.getShareLink();
            String link=param.getUrl();
            if(StringUtil.isNullOrEmpty(shareLink)){
                shareLink=link;
            }
            log.info("shareLink:{}",shareLink);
            log.info("link：{}",link);
            link=link.split("#")[0];
            log.info("#分割后link:{}",link);
            //获取当前微信登录账号信息
            String acId=param.getAcId();
            /*if(!redisService.exists(acId)) {
                resultModel.setCode(ResultStatus.ERROR.getCode());
                resultModel.setMessage("acId不正确");
                return resultModel;
            }*/
            WeiXinUserResult weiXinUserResult= (WeiXinUserResult) redisService.get(acId);

            long timestamp = System.currentTimeMillis() / 1000;
            String noncestr = RandomStr.createRandomString(16);
            WeiXinShareResult weiXinShareResult=new WeiXinShareResult();
            //查询问卷信息
            Question question= questionService.selectQuestion();
            if(!StringUtil.isNullOrEmpty(question)){
                String appid=question.getAppId();
                String secret=question.getAppSecret();
                JsApiTicketUtil jsApiTicketUtil=new JsApiTicketUtil();
                String jsApiTicketKey="jsapi_ticket";
                String ticket="";
                if(redisService.exists(jsApiTicketKey)){
                    ticket=redisService.get(jsApiTicketKey)+"";
                    log.info("缓存中存在jsapi_ticket：{}",ticket);
                }else{
                    ticket =jsApiTicketUtil.getJsapiTicket(appid,secret);
                    log.info("缓存中不存在jsapi_ticket，调用微信接口获取得到:{}",ticket);
                    long time=7200L;
                    redisService.set(jsApiTicketKey, ticket,time, TimeUnit.SECONDS);
                    log.info("将jsapi_ticket存放到缓存中。。。。。。。。。。");
                }
                String str = "jsapi_ticket=" + ticket + "&noncestr=" + noncestr + "&timestamp=" + timestamp + "&url=" + link;
                log.info("===============签名str：{}" , str);
                String signature = Sha1.encode(str);
                log.info("生成的签名：{}",signature);
                weiXinShareResult.setAppId(appid);
                weiXinShareResult.setTimestamp(timestamp+"");
                weiXinShareResult.setNonceStr(noncestr);
                weiXinShareResult.setSignature(signature);
                weiXinShareResult.setTitle(question.getShareTitle());
                weiXinShareResult.setDesc(question.getShareContent());
                //shareLink如果包含acId参数，需要去掉
                shareLink=UrlUtils.removeParam(shareLink, "acId");
                log.info("过滤后的shareLink:{}",shareLink);
                if(shareLink.contains("?")){
                    shareLink=shareLink+"&shareOpenId="+weiXinUserResult.getOpenId();
                }else{
                    shareLink=shareLink+"?shareOpenId="+weiXinUserResult.getOpenId();
                }
                shareLink=shareLink.replace("?&", "?");
                log.info("返回给前端的shareLink:{}",shareLink);
                weiXinShareResult.setLink(shareLink);
                weiXinShareResult.setImgUrl(question.getSharePic());
                resultModel.setCode(ResultStatus.SUCCESS.getCode());
                resultModel.setMessage(ResultStatus.SUCCESS.getMessage());
                resultModel.setData(weiXinShareResult);
            }
        }catch (Exception e){
            e.printStackTrace();
            resultModel.setCode(ResultStatus.ERROR.getCode());
            resultModel.setMessage("获取微信配置信息出错");
        }


        return resultModel;
    }



    @ApiOperation(notes = "获取分享者好友信息" , value = "获取分享者好友信息",response = WeiXinShareUserResult.class,position =3)
    @RequestMapping(value = "/getWeiXinShareUserInfo",method = RequestMethod.POST)
    public Object getWeiXinShareUserInfo(@Valid ShareOpenIdParam param, BindingResult bindingResult, HttpServletRequest request){
        ResultModel resultModel=new ResultModel();
        try{
            Map<String, Object> parameterMap= GetParamToMap.getParameterMap(request);
            Map<String, Object> jsonMap= GetParamToMap.getJosnParameterMap(request);
            log.info("传递过来的参数==="+ JSON.toJSONString(parameterMap)+"ip==="+ IpUtils.getIpAddr(request));
            log.info("传递过来的jsonMap参数==="+ JSON.toJSONString(jsonMap)+"ip==="+ IpUtils.getIpAddr(request));
            if (validParamService.validParam(bindingResult, resultModel)){
                return resultModel;
            }
           Map<String,Object> queryMap=new HashMap<>();
            queryMap.put("openId",param.getShareOpenId());
            Question question= questionService.selectQuestion();
            String questionId="-1";
            if(!StringUtil.isNullOrEmpty(question)) {
                Date startTime = question.getStartTime();
                Date endTime = question.getEndTime();
                questionId = DateUtil.format(startTime, DateUtils.YYYYMMDDHHMMSS) + DateUtil.format(endTime, DateUtils.YYYYMMDDHHMMSS);
                log.info("当前问卷id：{}", questionId);
            }

            log.info("查询微信好友信息：{}",JSON.toJSONString(queryMap));
            WeiXinUserResult weiXinUserResult= weixinUserService.selectWeixinUserByMap(queryMap);
            log.info("查询好友信息返回结果：{}",JSON.toJSONString(weiXinUserResult));
            WeiXinShareUserResult weiXinShareUserResult=new WeiXinShareUserResult();
            BeanUtil.copyProperties(weiXinUserResult,weiXinShareUserResult);
            log.info("属性赋值后的结果：{}",JSON.toJSONString(weiXinShareUserResult));
            queryMap.put("questionId",questionId);
            log.info("获取好友答题参数：{}",JSON.toJSONString(queryMap));
            DatiRecord datiRecord=datiRecordService.getMaxScroreRecord(queryMap);
            log.info("获取好友答题结果：{}",JSON.toJSONString(datiRecord));
            if(!StringUtil.isNullOrEmpty(datiRecord)) {
                weiXinShareUserResult.setScore(datiRecord.getScore() + "");
            }
            resultModel.setCode(ResultStatus.SUCCESS.getCode());
            resultModel.setMessage(ResultStatus.SUCCESS.getMessage());
            resultModel.setData(weiXinShareUserResult);
        }catch (Exception e){
            e.printStackTrace();
            resultModel.setCode(ResultStatus.ERROR.getCode());
            resultModel.setMessage("获取微信配置信息出错");
        }
        return resultModel;
    }


}

